package com.shioirikukuri.handler;

import com.shioirikukuri.domain.OrderInfo;
import com.shioirikukuri.domain.OrderInfoCanal;
import com.shioirikukuri.mq.MQConstant;
import com.shioirikukuri.redis.SeckillRedisKey;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

@Component
@CanalTable("t_order_info")
public class OrderInfoHandler implements EntryHandler<OrderInfoCanal> {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 插入
     * @param orderInfo
     */
    @Override
    public void insert(OrderInfoCanal orderInfo) {

        System.out.println("insert:" + JSON.toJSONString(orderInfo));
        if (orderInfo.getSeckill_id() == null) {
            // 处理 seckill_id 为 null 的情况
            System.err.println("Error: seckill_id is null.");
            return;
        }
        //在Redis中设置key，判断阻止用户重复下单
        String orderSetKey = SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(orderInfo.getSeckill_id().toString());
        redisTemplate.opsForSet().add(orderSetKey,orderInfo.getPhone());
    }




    /**
     * 更新
     * @param before
     * @param after
     */
    @Override
    public void update(OrderInfoCanal before, OrderInfoCanal after) {
        //打印插入前数据
        System.out.println("update before:" + JSON.toJSONString(before));
        //打印插入后数据
        System.out.println("update after:" + JSON.toJSONString(after));


        if(OrderInfo.STATUS_UNPAID.equals(before.getStatus()) && OrderInfo.STATUS_TIMEOUT.equals(after.getStatus())){
            //增加Redis内存====>涉及到MySql和Redis同步
            String stockCountKey = SeckillRedisKey.SECKILL_PRODUCT_STOCK.getRealKey((after.getSeckill_id().toString()));

            //创建订单失败，则回滚补库存
            //同步Redis中的库存
            redisTemplate.opsForValue().increment(stockCountKey);

            //不再依赖直接修改本地标识，而是通过MQ广播控制所有集成服务同时修改标识
            rocketMQTemplate.syncSend(MQConstant.STOCK_OVER_FLAG_TOPIC,after.getSeckill_id());
        }
    }

    @Override
    public void delete(OrderInfoCanal orderInfo) {
        System.out.println("delete:" + JSON.toJSONString(orderInfo));
    }
}
